import copy

class Process_data:
    def __int__(self,data):
        self.data=data

    def align_data(self,old_dict,all_materials):
        new_dict={}
        for m in all_materials:
            if(m not in old_dict.keys()):
                old_dict[m]=0
        new_dict = dict(sorted(old_dict.items(), key=lambda item: item[0]))
        return new_dict

    def process_data(self,data): #对to_nlp之后的数据进行处理
        all_materials=[]
        all_dcs_materials=[]
        merged_dict = {}
        for d in data:
            all_materials.extend(d['materialList'])
            all_dcs_materials.extend(list(d['feedbackIngredient'].keys()))
            for k,v in d['materialAnalysis'].items():
                if k not in merged_dict:
                    merged_dict[k] = v
        merged_dict = dict(sorted(merged_dict.items(), key=lambda item: item[0]))
        all_materials=sorted(list(set(all_materials)))
        all_dcs_materials=sorted(list(set(all_dcs_materials)))
        new_data=[]
        for i,d in enumerate(data):
            d['feedbackIngredient']=copy.deepcopy(self.align_data(d['feedbackIngredient'],all_dcs_materials))
            d['materialList']=copy.deepcopy(all_materials)
            d['materialAnalysis']=copy.deepcopy(merged_dict)
            new_data.append(d)
        return new_data

    def process_adm_ratio(self,data):
        for data_dict in data:
            # 加入混合材搭配比例
            # print(data_dict)
            adm_ratio = data_dict["admixtureRatio"]
            if adm_ratio != {}:
                feedback_wet = data_dict["feedbackIngredient"]
                for k, v in adm_ratio.items():
                    sum_num = feedback_wet[k]
                    deno = sum(v.values())
                    for k_1, v_1 in v.items():
                        feedback_wet[k_1] = sum_num * v_1 / deno
        return data

    def process_adm_ratio_single(self,data_dict):
        adm_ratio = data_dict["admixtureRatio"]
        if adm_ratio != {}:
            feedback_wet = data_dict["feedbackIngredient"]
            for k, v in adm_ratio.items():
                sum_num = feedback_wet[k]
                deno = sum(v.values())
                for k_1, v_1 in v.items():
                    feedback_wet[k_1] = sum_num * v_1 / deno